import pyautogui
import pytesseract
from PIL import Image
import random
import time

# 设置 Tesseract 可执行文件路径
pytesseract.pytesseract.tessdata_dir = r'D:\Program Files\Tesseract-OCR'
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract.exe'
# pytesseract.pytesseract.tessdata_dir_config = r'--tessdata-dir "D:\Program Files\Tesseract-OCR\tessdata"'
testdata_dir_config = '--tessdata-dir "D:\\Program Files\\Tesseract-OCR\\tessdata"'


def capture_screen_and_check_text():
    # 截取整个屏幕，若只需要特定区域，使用 pyautogui.screenshot(region=(x, y, width, height))
    screenshot = pyautogui.screenshot()
    screenshot.save("screen_capture.png")

    # 打开并识别截图中的文字
    filePath = "C:\\Users\\lizhi\\Pictures\\zhifubao_20241025093627.jpg"
    img = Image.open(filePath)
    # https://tesseract-ocr.github.io/tessdoc/Data-Files
    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
    print(data)
    # 遍历并打印每个单词的文本及其位置
    for i in range(len(data['text'])):
        if data['text'][i].strip() != '':  # 只处理非空字符
            print(f"Text: {data['text'][i]}, "
                  f"Position: ({data['left'][i]}, {data['top'][i]}), "
                  f"Width: {data['width'][i]}, Height: {data['height'][i]}")

    # text = pytesseract.image_to_string(img,  config=testdata_dir_config, lang='chi_sim')  # 'chi_sim' 用于中文识别
    # print(text)
    text = pytesseract.image_to_string(img)
    print(text)
    # 检查是否包含 "短剧" 两个字
    if "短剧" in text:
        num = 50
        sleep_time = random.randint(16, 20)
        print(f"检测到 '短剧'，num = {num}, sleep_time = {sleep_time}")

        # 根据随机生成的 sleep_time 进行延迟
        time.sleep(sleep_time)
    else:
        print("未检测到 '短剧'")

# 调用函数
capture_screen_and_check_text()